package cn.com.duiba.millionaire.center.biz.remoteservice;

import cn.com.duiba.millionaire.center.api.dto.CreditsConsumeLogDto;
import cn.com.duiba.millionaire.center.api.enums.CreditsConsumeStatusTypeEnum;
import cn.com.duiba.millionaire.center.api.param.CreditsConsumeRequestParam;
import cn.com.duiba.millionaire.center.api.param.ValidTicket4MillionaireSearchParam;
import cn.com.duiba.millionaire.center.api.remoteservice.RemoteCreditsConsumeService;
import cn.com.duiba.millionaire.center.biz.service.CreditsConsumeLogService;
import cn.com.duiba.millionaire.center.biz.service.CreditsConsumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by xiaoxuda on 2018/2/12.
 */
@RestController
public class RemoteCreditsConsumeServiceImpl implements RemoteCreditsConsumeService {
    @Autowired
    private CreditsConsumeLogService creditsConsumeLogService;
    @Autowired
    private CreditsConsumeService creditsConsumeService;

    @Override
    public Long applyCreditsConsume(CreditsConsumeRequestParam param) {
        CreditsConsumeLogDto dto = new CreditsConsumeLogDto();
        dto.setConsumerId(param.getConsumerId());
        dto.setPartnerUserId(param.getPartnerUserId());
        dto.setAppId(param.getAppId());
        dto.setBizType(param.getBizType());
        dto.setBizNo(param.getBizNo());
        dto.setCredits(param.getCredits());
        dto.setEnvIp(param.getEnvIp());
        dto.setConStatus(CreditsConsumeStatusTypeEnum.PROCESSING);
        Long logId = creditsConsumeLogService.insert(dto);

        creditsConsumeService.apply(param, logId);
        return logId;
    }

    @Override
    public CreditsConsumeLogDto findById(Long id) {
        return creditsConsumeLogService.findById(id);
    }

    @Override
    public CreditsConsumeLogDto findValidTicket4Millionaire(ValidTicket4MillionaireSearchParam param) {
        List<CreditsConsumeLogDto> list = creditsConsumeLogService.findNoFailByConsumerIdAndBizTypeAndBizId(
                param.getConsumerId(), param.getBizType(), param.getBizNo());
        CreditsConsumeLogDto result = null;
        for(CreditsConsumeLogDto dto : list){
            if(CreditsConsumeStatusTypeEnum.SUCCESS.equals((result = dto).getConStatus())){
                return result;
            }
        }
        return result;
    }
}
